// 文本内容复制指令 v-copy
import { ElMessage } from "element-plus"
export default {
  mounted(el, binding) {
    let div = document.createElement('div');
    el.parentNode.addEventListener('mouseenter', (e) => {
      div.innerText = '复制';
      div.style.position = 'absolute';
      div.style.zIndex = 1000;
      div.addEventListener('click', () => {
        handleClick(el.innerText)
      })
      el.parentNode.style.position = 'relative';
      div.style.top = 0;
      div.style.left = '50%';
      div.style.boxSizing = 'border-box';
      div.style.padding = '0px 6px';
      div.style.border = '1px solid yellowgreen';
      div.style.cursor = 'pointer';
      div.style.fontSize = '10px';
      div.style.borderRadius = '6px';
      div.style.backgroundColor = 'yellowgreen';
      div.style.width = `${el.parentNode.clientX * 0.4}px`;
      el.parentNode.appendChild(div)
      // console.log('鼠标移入', div)
    })

    el.parentNode.addEventListener('mouseleave', () => {
      // console.log('鼠标移出', el.innerText)
      el.parentNode.style.position = '';
      el.parentNode.removeChild(div)
    })
  },
  unmounted(el) {
    // el.parentNode.removeEventListener('mouseover')
    // el.parentNode.removeEventListener('mouseover')
  },
}

function handleClick(text) {
  // 创建元素
  if (!document.getElementById('copyTarget')) {
    const copyTarget = document.createElement('input')
    copyTarget.setAttribute('style', 'position:fixed;top:0;left:0;opacity:0;z-index:-1000;')
    copyTarget.setAttribute('id', 'copyTarget')
    document.body.appendChild(copyTarget)
  }
  // 复制内容
  const input = document.getElementById('copyTarget')
  input.value = text
  input.select()
  document.execCommand('copy')
  ElMessage({
    type: 'success',
    message: '复制成功',
    showClose: true,
    grouping: true,
    duration: 1 * 1000,
    customClass: 'messageClass'
  })
  document.body.removeChild(copyTarget)
}